import { getToken } from '../functions/token';
const baseUrl = 'http://localhost:2303/api';
const baseImagesUrl = 'http://localhost:2303/Uploads/Images/';


interface Request {
  get: (url: string, params?: any, headers?:any) => Promise<ApiResponse>;
  post: (url: string, params?: any, headers?:any) => Promise<ApiResponse>;
}
const paramsToQueryString = (params: any) => {
  return Object.keys(params)
    .map(
      (key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
    )
    .join('&');
};

const fetchInstance = (
  url: string,
  options: RequestInit
): Promise<ApiResponse> => {
  return fetch(baseUrl + url, {
    ...options,
    method: options?.method,
    headers: {
      'Content-Type': 'application/json',
      Authorization: 'Bearer ' + getToken(),
      ...options?.headers,
    },
  })
    .then((res) => {
      try {
        if (res.status > 300) {
          switch (res.status) {
            case 401:
              return getPromiseApiResponse(-1, '未登录或登录已过期', {
                res: res,
              });
            case 403:
              return getPromiseApiResponse(-1, '无权限访问', { res: res });
            case 404:
              return getPromiseApiResponse(-1, '资源不存在', { res: res });
            case 500:
              return getPromiseApiResponse(-1, '服务器错误', { res: res });
            default:
              break;
          }
        }
        return res.json() as Promise<ApiResponse>;
      } catch (e) {
        return getPromiseApiResponse(-1, '无响应数据或响应格式错误', {
          res: res,
          error: e,
        });
      }
    })
    .catch((e) => {
      console.error(e);
      return getPromiseApiResponse(-1, '网络错误', {
        error: e,
      });
    });
};

function getPromiseApiResponse(
  code: ResponseCode,
  message: string,
  data: any
): Promise<ApiResponse> {
  return new Promise((resolve, reject) => {
    var d = {
      code: code,
      message: message,
      data: data,
    } as ApiResponse;
    resolve(d);
  }) as Promise<ApiResponse>;
}

const request: Request = {
  get: function (
    url: string,
    params: any = {},
    headers:any={}
  ): Promise<ApiResponse> {
    let paramsStr: string = paramsToQueryString(params);
    return fetchInstance(url + (paramsStr ? '?' + paramsStr : ''), {
      method: 'GET',
      headers:headers
    });
  },
  post: function (
    url: string,
    params: any = {},
    headers:any={}
  ): Promise<ApiResponse> {
    return fetchInstance(url, {
      method: 'POST',
      body: (headers['Content-Type'] === 'multipart/form-data; boundary=----WebKitFormBoundaryDXEdyjl3aBEfJ5Ay')?params: JSON.stringify(params),
      headers:headers
    });
  },
};

export { request, baseUrl, baseImagesUrl };
